package com.gwlc.common.util.file;

import com.gwlc.common.config.LuckyConfig;
import com.gwlc.common.exception.file.FileNotTypeException;
import com.gwlc.common.exception.file.FileNullException;
import com.gwlc.common.exception.file.FileSizeOverrunException;
import com.gwlc.common.exception.file.image.ImageSaveFailException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>lucky-com.gwlc.common.util-FileTool</p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date
 */


public class FileTool extends FilenameUtils {
    /**
     * 文件类型
     */
    public final static Map<String, String> FILE_TYPE_MAP = new HashMap<>();

    /**
     * 文件根目录
     */
    private static final String SAVE_PATH = LuckyConfig.getSavaPath();
    /**
     * 文件大小限制
     */
    private static final Long MAX_SIZE = LuckyConfig.getMaxFileSize();

    static {
        getAllFileType();  //初始化文件类型信息
    }


    private static void getAllFileType() {
        FILE_TYPE_MAP.put("jpg", "FFD8FF");
        FILE_TYPE_MAP.put("png", "89504E47");
        FILE_TYPE_MAP.put("gif", "47494638");
        FILE_TYPE_MAP.put("tif", "49492A00");
        FILE_TYPE_MAP.put("bmp", "424D");
        FILE_TYPE_MAP.put("dwg", "41433130");
        FILE_TYPE_MAP.put("html", "68746D6C3E");
        FILE_TYPE_MAP.put("rtf", "7B5C727466");
        FILE_TYPE_MAP.put("xml", "3C3F786D6C");
        FILE_TYPE_MAP.put("zip", "504B0304");
        FILE_TYPE_MAP.put("rar", "52617221");
        FILE_TYPE_MAP.put("psd", "38425053");
        FILE_TYPE_MAP.put("eml", "44656C69766572792D646174653A");
        FILE_TYPE_MAP.put("dbx", "CFAD12FEC5FD746F");
        FILE_TYPE_MAP.put("pst", "2142444E");
        FILE_TYPE_MAP.put("xls", "D0CF11E0");
        FILE_TYPE_MAP.put("doc", "D0CF11E0");
        FILE_TYPE_MAP.put("mdb", "5374616E64617264204A");
        FILE_TYPE_MAP.put("wpd", "FF575043");
        FILE_TYPE_MAP.put("eps", "252150532D41646F6265");
        FILE_TYPE_MAP.put("ps", "252150532D41646F6265");
        FILE_TYPE_MAP.put("pdf", "255044462D312E");
        FILE_TYPE_MAP.put("qdf", "AC9EBD8F");
        FILE_TYPE_MAP.put("pwl", "E3828596");
        FILE_TYPE_MAP.put("wav", "57415645");
        FILE_TYPE_MAP.put("avi", "41564920");
        FILE_TYPE_MAP.put("ram", "2E7261FD");
        FILE_TYPE_MAP.put("rm", "2E524D46");
        FILE_TYPE_MAP.put("mpg", "000001BA");
        FILE_TYPE_MAP.put("mov", "6D6F6F76");
        FILE_TYPE_MAP.put("asf", "3026B2758E66CF11");
        FILE_TYPE_MAP.put("mid", "4D546864");
    }


    public static List<Object> listPathFiles(String path) {

        return null;
    }

    /**
     * 递归连接url
     *
     * @param paths    路径的集合或者键值对
     * @param basePath 父级地址
     * @return 拼接完成后的地址集合或者键值对
     */
    public static Object joinUrl(Object paths, String basePath) {

        if (paths instanceof Map) {
            Map<String, Object> newPath = new HashMap<>();
            for (Map.Entry<String, Object> entry : ((Map<String, Object>) paths).entrySet()) {
                newPath.put(entry.getKey(), FileTool.joinUrl(entry.getValue(), basePath + "/" + entry.getKey()));
            }
            return newPath;
        } else if (paths instanceof List) {
            List<Object> newPath = new ArrayList<>();
            for (Object path : (List<Object>) paths) {
                newPath.add(FileTool.joinUrl(path, basePath));
            }
            return newPath;
        } else if (paths instanceof String) {
            return basePath + paths;
        }
        return paths;
    }

    public static Boolean saveFile(String path, String fileName, String fileSuffix, CommonsMultipartFile file) throws IOException {

        path = path + "/" + fileName + fileSuffix;

        file.transferTo(new File(path));
        return true;
    }


    public static String fileUpload(String path, String fileName, String fileSuffix, MultipartFile file) {
        //检查图片是否为空
        if (file == null || file.isEmpty()) {
            throw new FileNullException();
        }

        //判断图片大小是否符合要求
        if (file.getSize() > MAX_SIZE) {
            throw new FileSizeOverrunException();
        }

        // 文件原名称
        String oldFileName = file.getOriginalFilename();
        // 文件类型
        String type = null;
        //System.out.println("上传的文件原名称:" + oldFileName);
        // 判断文件类型
        type = oldFileName.contains(".") ? oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length()) : null;
        // 判断文件类型是否为空
        if (type != null) {


            // 项目在容器中实际发布运行的根路径
            //   String realPath = request.getSession().getServletContext().getRealPath("/");
            // 自定义的文件名称
            // 设置存放图片文件的路径
            String trueFileName = fileName + fileSuffix;
            System.out.println("存放图片文件的路径:" + SAVE_PATH);
            File file1 = new File(SAVE_PATH + path);

            // 文件对象创建后，指定的文件或目录不一定物理上存在
            if (!file1.exists()) {
                if (!file1.mkdir()) {
                    throw new ImageSaveFailException();
                }
            }
            // 转存文件到指定的路径
            try {
                file.transferTo(new File(SAVE_PATH + path + trueFileName));
            } catch (IOException e) {
                throw new ImageSaveFailException();
            }
            System.out.println("文件成功上传到指定目录下");
            return path + trueFileName;

        } else {
            System.out.println("文件类型为空");
            throw new FileNotTypeException();
        }
    }

}
